/**
 * @file Axios 全局配置
 */
import axios from "axios";
import { baseURl } from "../index";

const myAxios = axios.create({
  baseURL: baseURl() + "api/", // 测试
  // withCredentials: true,
  timeout: 10000,
});

myAxios.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = localStorage.getItem("token");
    return config;
  },
  (err) => {
    var error = {
      message: "网络异常，请刷新重试",
      err: err,
      type: "requestError",
    };
    return Promise.reject(error);
  }
);

myAxios.interceptors.response.use(
  (res) => {
    if (res.data.code == 10001) {
      console.log("登录过期");
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      window.location.reload();
      return;
    }
    if (res.status >= 200 && res.status < 300) {
      return res;
    }
    return Promise.reject(res);
  },
  (error) => {
    // 网络异常
    if (axios.isCancel(error)) {
      let err = {
        message: "路由切换，网络请求已取消",
        err: error,
        type: "cancel",
      };
      return Promise.reject(err);
    } else {
      let err = {
        message: "网络异常，请刷新重试",
        err: error,
        type: "responseError",
      };
      return Promise.reject(err);
    }
  }
);

export default myAxios;
